package com.kotlin.android.platoon.app.activity

import android.os.Bundle
import android.text.TextUtils
import android.util.Base64
import com.android.app.api.config.ServiceConfig
import com.kotlin.android.platoon.app.MainActivity
import com.kotlin.android.app.openAppByScheme
import com.kotlin.android.core.BaseActivity
import com.kotlin.android.ktx.ext.log.d

class RouterActivity : BaseActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val dataString = intent?.dataString
        val data = intent?.data
        if (data != null) {
            val scheme = data.scheme
            val host = data.host
            val path = data.path
            val authority = data.authority
            val port = data.port
            val query = data.encodedQuery.orEmpty()
            val msg = "\n${dataString.orEmpty()}\nscheme:$scheme\nhost:$host\npath:$path\nauthority:$authority\nport:$port\nquery:$query"
            "Scheme >>> msg=$msg".d()
            ServiceConfig.instance.schemeQuery = getSchemeQueryValueString(query)
            openAppByScheme(MainActivity::class.java)
        }
        finish()
    }

    private fun getSchemeQueryValueString(queryString: String? = ""): String {
        if (TextUtils.isEmpty(queryString)) {
            return ""
        }
        val key ="openApp="
        var queryMapString = queryString?.split("&")?.asSequence()?.filter { it.startsWith(key) }?.firstOrNull().orEmpty()
        queryMapString = if (queryString?.endsWith("?") == true) {
            queryMapString.substring(key.length, queryString.length - 1)
        }else{
            queryMapString.substring(key.length, queryString?.length?:0)
        }
        val decode = Base64.decode(queryMapString, Base64.DEFAULT)
        return String(decode)
    }

}
